from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db.models import PositiveIntegerField, TextField
from extensions.models import *


# 省市区县区域
class Region(Model):
    id = CharField(max_length=255, unique=True, blank=True,verbose_name='地区主键编号',primary_key=True)
    region_name = CharField(max_length=255, unique=True, blank=True,verbose_name='地区名称')
    region_short_name = CharField(max_length=255, null=True,unique=True, blank=True,verbose_name='地区缩写')
    region_parent_id = CharField(max_length=255, blank=True,verbose_name='地区父id')
    index = IntegerField(unique=True,default=None, blank=True, verbose_name='序号')
    region_level = IntegerField(default=None, blank=True, verbose_name='地区级别 1-省、自治区、直辖市 2-地级市、地区、自治州、盟 3-市辖区、县级市、县')


class Job(Model):
    index = IntegerField(unique=True, default=None, blank=True, verbose_name='序号')
    name = CharField(max_length=255, unique=True, blank=True,verbose_name='职务名称')


class PermissionGroup(Model):
    """权限分组"""

    name = CharField(max_length=64, verbose_name='分组名称')


class Permission(Model):
    """权限"""

    group = ForeignKey('system.PermissionGroup', on_delete=CASCADE, related_name='permissions', verbose_name='权限分组',db_constraint=False)
    name = CharField(max_length=64, verbose_name='权限名称')
    code = CharField(max_length=64, verbose_name='权限代码')


class Role(Model):
    """角色"""

    name = CharField(max_length=64, verbose_name='名称')
    remark = CharField(max_length=256, null=True, blank=True, verbose_name='备注')
    permissions = ManyToManyField('system.Permission', blank=True, related_name='roles', verbose_name='权限',db_constraint=False)

#版本号
class Version(Model):
    """版本号"""
    name = CharField(max_length=64, verbose_name='版本号')
    remark = CharField(max_length=256, null=True, blank=True, verbose_name='备注')
    # permissions = ManyToManyField('system.Permission', blank=True, related_name='roles', verbose_name='权限')

#组织
class Organization(Model):
    """组织"""
    name = CharField(max_length=64, verbose_name='组织名称')
    parent = ForeignKey('self', on_delete=SET_NULL, null=True, blank=True, related_name='children', verbose_name='上级组织', db_constraint=False)
    coding_abbreviation = CharField(max_length=255, unique=False, blank=True, verbose_name='公司编码缩写')
    organization_level = IntegerField(default=None, blank=True, verbose_name='组织级别 1-省分公司、2-省分公司部门或地市分公司 3-地市分公司部门或县分公司')
    index = IntegerField(unique=False, default=None, blank=True, verbose_name='序号')
    type = IntegerField(default=None, blank=True, verbose_name='组织类型 1-省分公司、2-省分公司部门、3-地市分公司 4-地市分公司部门、5-县分公司')

    class Meta:
        unique_together = (('name', 'parent',),('organization_level', 'index',),)


class User(Model):
    """用户"""
    name = CharField(max_length=64, verbose_name='姓名')
    phone = CharField(unique=True,max_length=32, null=True, blank=True, verbose_name='手机号')
    email = CharField(max_length=256, null=True, blank=True, verbose_name='邮箱')
    roles = ManyToManyField('system.Role', blank=True, related_name='User_roles', verbose_name='角色', db_constraint=False)
    permissions = ManyToManyField(Permission, blank=True, verbose_name='权限', db_constraint=False)
    is_superuser = BooleanField(default=False, verbose_name='超级用户')
    is_active = BooleanField(default=True, verbose_name='激活状态')
    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = DateTimeField(auto_now=True, verbose_name='更新时间')
    last_login = DateTimeField(auto_now=True, verbose_name='最后登录时间')
    avatar = ImageField(upload_to='avatars/', null=True, blank=True, verbose_name='头像')
    is_staff = BooleanField(default=False, verbose_name='员工状态')
    organization = ForeignKey('system.Organization', on_delete=CASCADE, blank=True, default=None, related_name='User_organization', db_constraint=False)
    job = ForeignKey('system.Job', on_delete=CASCADE, blank=True, default=None, related_name='User_job', db_constraint=False)

    class Meta:
        unique_together = (('name', 'phone',),)

    def __str__(self):
        return self.name

    #获取用户是否有某个权限
    def has_perm(self, perm):
        if self.is_active and self.is_superuser:
            return True
        return self.permissions.filter(code=perm).exists()



class Dict(Model):
    """数据字典"""
    id = CharField(max_length=32, verbose_name='id',primary_key=True)
    name = CharField(unique=True,max_length=64, verbose_name='字典名称')
    code = CharField(unique=True,max_length=64, verbose_name='字典编码')
    description = CharField(max_length=64,  blank=True, default=None,verbose_name='字典描述')
    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间')


class Dict_item(Model):
    """数据字典"""
    id = CharField(max_length=32, verbose_name='id',primary_key=True)
    dict = ForeignKey(Dict, on_delete=CASCADE, blank=True, default=None, related_name='dict_item',db_constraint=False)
    name = CharField(max_length=64, verbose_name='选项名称')
    index = IntegerField(unique=False, default=None, blank=True, verbose_name='序号')
    description = CharField(max_length=64, blank=True, default=None,verbose_name='选项描述')

    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        unique_together = [('dict', 'name')]

"""
登录日志
"""
class LoginLog(Model):
    user = ForeignKey(User, on_delete=CASCADE, blank=True, default=None, related_name='LoginLog',db_constraint=False)
    ip_address  = CharField(max_length=64, verbose_name='ip地址')
    user_agent   = CharField(max_length=512, verbose_name='用户代理')
    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间')

class Check(Model):
    """通用审核记录"""
    content_type = ForeignKey(ContentType, on_delete=CASCADE,db_constraint=False)
    object_id = PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    opinion = CharField(max_length=1024, verbose_name='审核意见', null=True, blank=True)
    is_agree = BooleanField(default=True,verbose_name='是否同意') # False=不同意，True=同意
    check_user = ForeignKey('system.User', on_delete=SET_NULL,null=True,blank=True, default=None,verbose_name='审核人',db_constraint=False)
    create_time =DateTimeField(auto_now_add=True, verbose_name='审核时间')

    class Meta:
        verbose_name = '审核记录'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.check_user.name

#工作流
class Workflow(Model):
    name = CharField(max_length=255)
    model_name = CharField(max_length=255, null=True, blank=True, verbose_name='模型名称', help_text='模型名称', default=None)

#工作流步骤
class WorkflowStep(Model):
    workflow = ForeignKey(Workflow, related_name='steps', on_delete=CASCADE,db_constraint=False)
    name = CharField(max_length=255)  # new name field
    step_number = PositiveIntegerField()
    approval_permission = ForeignKey(Permission, on_delete=SET_NULL, null=True, blank=True,db_constraint=False)
    is_final_step = BooleanField(default=False)

#操作记录
class OperationRecord(Model):
    content_type = ForeignKey(ContentType, on_delete=CASCADE,db_constraint=False)
    object_id = PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    user = ForeignKey(User, on_delete=CASCADE, blank=True, default=None, related_name='OperationRecord_user',db_constraint=False)
    request_method = CharField(max_length=20)
    request_path = CharField(max_length=255)
    url_name = CharField(max_length=255, blank=True, null=True)
    request_params = TextField(blank=True, null=True)  # new field
    response_status = IntegerField()
    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间')
    del_flag = BooleanField(verbose_name='删除标识', default=False)
    class Meta:
        verbose_name = '操作记录'
        verbose_name_plural = verbose_name
        ordering = ['-create_time']

    def __str__(self):
        return self.request_method


__all__ = [
    'PermissionGroup', 'Permission', 'Role', 'User',
    'Job',
    'Dict',
    'Dict_item',
    'LoginLog',
]
